import styled from "@emotion/styled";
import { Drawer, Form, Spin, Input, Button, Switch } from "antd";
import { DrawerProps } from "antd/es/drawer";
import { useForm } from "antd/lib/form/Form";
import { ErrorBox } from "components/lib";
import { UploadImage } from "components/upload-image";
import { useEffect, useState } from "react";
import { useAddLabel, useModifyLabel, useLabelParam } from "./util";
import { UploadFile, UploadChangeParam } from "antd/lib/upload/interface";

export const CreateLabel = (
  props: Pick<DrawerProps, "visible"> & { onClose: () => void }
) => {
  const { mutateAsync: addLabel, isLoading: isAddLoading } = useAddLabel();

  const { mutateAsync: modifyLabel, isLoading: isModifyLoading } =
    useModifyLabel();

  const [form] = useForm();
  const [img, setImg] = useState<UploadFile[]>([]);
  const [messageError, setMessageError] = useState<Error | null>(null);

  const { label, isLoading, id } = useLabelParam();

  useEffect(() => {
    setMessageError(null);
    // setImg([]);
    if (label) {
      const formValue = {
        ...label,
        status: label.status === 1 ? true : false,
        img: label.img,
      };
      setImg([
        {
          uid: "1",
          url: label.img,
          name: label.img,
          status: "done",
        },
      ]);
      form.setFieldsValue(formValue);
    } else {
      form.resetFields();
      form.setFieldsValue({ status: true, img: "" });
    }
  }, [form, props.visible, label]);

  const onFinish = async (values: any) => {
    const status = form.getFieldsValue().status ? 1 : 2;
    let imgImport = "";
    if (img.length > 0) {
      imgImport = img[0].response ? img[0].response.key : img[0].url;
    }

    if (label) {
      await modifyLabel({
        ...form.getFieldsValue(),
        id,
        img: imgImport,
        status,
      })
        .then(() => {
          props.onClose();
        })
        .catch((error) => {
          error = setMessageError(new Error(error.message));
        });
    } else {
      await addLabel({ ...form.getFieldsValue(), img: imgImport, status })
        .then(() => {
          props.onClose();
        })
        .catch((error) => error);
    }
  };

  const changeImage = (info: UploadChangeParam<UploadFile<any>>) => {
    if (info.file.status === "removed") {
      setImg([]);
    }
    if (info.file.status === "done") {
      setImg(info.fileList);
    }
  };

  return (
    <Drawer
      visible={props.visible}
      onClose={props.onClose}
      forceRender={true}
      destroyOnClose={true}
      width={"100%"}
    >
      <Container>
        {isAddLoading || isModifyLoading || isLoading ? (
          <Spin size={"large"} />
        ) : (
          <>
            <h2>{label ? "编辑" + label.title : "创建标签"}</h2>
            <ErrorBox error={messageError} />
            <Form
              form={form}
              layout={"vertical"}
              style={{ width: "40rem" }}
              onFinish={onFinish}
            >
              <Form.Item
                label={"名称"}
                name={"title"}
                rules={[{ required: true, message: "请输入名称 " }]}
              >
                <Input placeholder="请输入名称" />
              </Form.Item>

              <Form.Item label={"状态"} name={"status"} valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>

              <Form.Item label={"图片"}>
                <UploadImage
                  modalTitle={"裁切图片"}
                  aspect={1}
                  nums={1}
                  onChange={changeImage}
                  value={img}
                />
              </Form.Item>

              <Form.Item style={{ textAlign: "right" }}>
                <Button
                  loading={isAddLoading || isModifyLoading}
                  type={"primary"}
                  htmlType={"submit"}
                >
                  提交
                </Button>
              </Form.Item>
            </Form>
          </>
        )}
      </Container>
    </Drawer>
  );
};

const Container = styled.div`
  height: 80vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
`;
